package api

import (
	"errors"

	"go_iot/apps/base"
	"go_iot/apps/product/entity"
	"go_iot/apps/response"

	"github.com/kataras/iris/v12"
)

func InitRouter(iris *iris.Application) {
	v1 := iris.Party("/product")
	{
		v1.Get("/list", getProductList)
		v1.Get("/item", getProductItem)
		v1.Get("/profile-get", getProductProfile)
		v1.Delete("/delete", delProduct)
		v1.Delete("/profile-del", delProductProfile)
		v1.Post("/add", addProduct)
		v1.Post("/profile-addmodbus", addModbusProfile)
	}
}

func addProduct(ctx iris.Context) {
	var p entity.Product

	if err := ctx.ReadJSON(&p); err != nil {
		response.JsonError(ctx, err)
		return
	}
	p.UserId = ctx.Value("client").(int)
	if err := base.CreateItem(&p); err != nil {
		response.JsonError(ctx, err)
		return
	}

	response.JsonMsg(ctx, "成功")
}

func getProductList(ctx iris.Context) {
	name := ctx.URLParam("name")
	user := ctx.Value("client").(int)

	page := ctx.URLParamIntDefault("page", 1)
	pageSize := ctx.URLParamIntDefault("pageSize", 10)
	var p = entity.Product{
		Name:   name,
		UserId: user,
	}
	m := p.SearchMap()
	if m == nil {
		response.JsonError(ctx, errors.New("错误请求"))
		return
	}
	pl, total := base.GetListPage[entity.Product](m, page, pageSize)

	response.JSONPagination(ctx, pl, total)
}

func getProductItem(ctx iris.Context) {
	id, err := ctx.URLParamInt("id")
	if err != nil {
		response.JsonError(ctx, err)
		return
	}

	p := base.GetItem[entity.Product](id)

	response.JsonSuccess(ctx, p)
}

func delProduct(ctx iris.Context) {
	id, err := ctx.URLParamInt("id")
	if err != nil {
		response.JsonError(ctx, err)
		return
	}
	err = base.DeleteItem[entity.Product](id)
	if err != nil {
		response.JsonError(ctx, err)
		return
	}
	response.JsonMsg(ctx, "成功")
}

func addModbusProfile(ctx iris.Context) {
	var m entity.ModbusProfile

	if err := ctx.ReadJSON(&m); err != nil {

		response.JsonError(ctx, err)
		return
	}
	var p = entity.ProductProfile{
		ProductId: m.Product,
		Type:      "modbus",
		Profile:   m,
	}
	err := p.CreateModbusItem(ctx)
	if err != nil {

		response.JsonError(ctx, err)
		return
	}
	response.JsonMsg(ctx, "success")
}

func getProductProfile(ctx iris.Context) {
	product := ctx.URLParam("product")
	t := ctx.URLParam("type")

	if product == "" || t == "" {
		response.JsonError(ctx, errors.New("参数错误"))
		return
	}

	p, err := entity.GetProductProfile(ctx, t, product)
	if err != nil {
		response.JsonError(ctx, errors.New("内部错误"))
		return
	}

	response.JsonSuccess(ctx, p)
}

func delProductProfile(ctx iris.Context) {
	id := ctx.URLParam("key")
	if id == "" {
		response.JsonError(ctx, errors.New("参数错误"))
		return
	}

	err := entity.DelProductProfile(ctx, id)

	if err != nil {
		response.JsonError(ctx, errors.New("内部错误"))
		return
	}

	response.JsonMsg(ctx, "success")
}
